const md5 = require('md5.js')
const baseUrl = 'https://mozi.bailingyoupin.com/api/'
const header = {
    'content-type': 'application/x-www-form-urlencoded'
}

const sendRequest = {
    post: function(url, data) {
        let sign = 'mozi'
        let timestamp = Date.parse(new Date())
        if (wx.getStorageSync('token')) {
            data.key = wx.getStorageSync('token')
        }
        data.login_type = 2
        data.timestamp = timestamp
        data = objKeySort(data)
        for (let i in data) {
            sign += (i + data[i])
        }
        sign += 'mozi'
        sign = md5(sign)
        data.sign = sign
        return new Promise((resolve, reject) => {
            wx.request({
                url: baseUrl + url,
                header: header,
                method: 'POST',
                data: data,
                success: function(res) {
                    let code = res.data.code
                    if (code === 200) {
                        resolve(res.data.datas)
                    } else if (code === 201) {
                        if (!wx.getStorageSync('loginStatus')) {
                            console.log('登录超时')
                            let page = getCurrentPages()
                            let currentPage = page[page.length - 1]
                            wx.setStorageSync('loginStatus', true)
                            wx.hideLoading()
                            wx.showModal({
                                title: '提示',
                                content: '是否前往登录',
                                success(res) {
                                    if (res.confirm) {
                                        if (currentPage == undefined || currentPage == null) {
                                            return
                                        } else {
                                            if (currentPage.route == 'pages/user/login/login' || currentPage.route == 'pages/user/bindPhone/bindPhone') {
                                                return
                                            } else {
                                                wx.login({
                                                    success(res) {
                                                        wx.setStorageSync('code', res.code)
                                                    }
                                                })
                                                getCurrentPageUrlWithArgs()
                                                wx.setStorageSync('loginStatus', true)
                                                wx.redirectTo({
                                                    url: '/pages/user/login/login',
                                                })
                                            }
                                        }
                                    } else if (res.cancel) {
                                        currentPage.data.isLoading = false
                                        wx.setStorageSync('loginStatus', false)
                                        if (currentPage.route == 'pages/goods/goodsDetail/goodsDetail' || currentPage.route == 'pages/zeroBuy/detail/detail') {
                                            return
                                        } else {
                                            if (page.length == 1) {
                                                wx.switchTab({
                                                    url: '/pages/index/index'
                                                })
                                            } else {
                                                wx.navigateBack({
                                                    delta: 1
                                                })
                                            }
                                        }
                                    }
                                }
                            })
                        }
                    } else if (code === 204) {
                        resolve(res.data)
                    }
                },
                fail: function(err) {
                    wx.showToast({
                        title: '网络繁忙',
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        }).catch(function(err) {
            wx.showToast({
                title: '网络繁忙',
                icon: 'none',
                duration: 2000
            })
        })
    }
}

const uploadImage = (tempFilePaths, tempUrl, tempData) => {
    return new Promise((presolve, preject) => {
        wx.showLoading({
            title: '上传图片中...'
        })
        let uploads = [] //定义方法数组
        tempFilePaths.forEach((item, i) => {
            uploads[i] = new Promise((resolve) => {
                wx.uploadFile({
                    url: tempUrl,
                    filePath: item,
                    name: 'file',
                    formData: tempData,
                    success(res) {
                        resolve(JSON.parse(res.data).datas)
                    },
                    fail(err) {
                        console.log(err)
                        wx.hideLoading()
                    }
                })
            })
        })

        Promise.all(uploads).then(res => {
            //图片上传完成
            presolve(res)
            wx.hideLoading()
        }).catch(err => {
            preject(err)
            wx.hideLoading()
            wx.showToast({
                title: '上传失败请重试',
                icon: 'none'
            })
        })

    })
}

function getCurrentPageUrlWithArgs() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options

    //拼接url的参数
    var urlWithArgs = url + '?'
    for (var key in options) {
        var value = options[key]
        urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

    wx.setStorageSync('prePageUrl', '/' + urlWithArgs)
}

function objKeySort(obj) {
    let newkey = Object.keys(obj).sort()
    let newObj = {}
    for (let i = 0; i < newkey.length; i++) {
        newObj[newkey[i]] = obj[newkey[i]]
    }
    return newObj
}

function refreshPage() {
    let page = getCurrentPages().pop(); //获取当前页面实例
    if (page == undefined || page == null) return;
    page.onLoad(page.options); //调用实例的onLoad方法重新加载数据;
    page.onShow();
}

module.exports = {
    post: sendRequest.post,
    refresh: refreshPage,
    uploadImage: uploadImage
}